package hos.soap;

import org.ksoap2.serialization.SoapSerializationEnvelope;

import hos.http.HttpSoapUtils;
import hos.http.HttpTag;
import hos.okhttp.http.OkHttpInterceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * <p>Title: OkHttpSoapInterceptor </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2024-04-05 20:52
 */
public class SoapOkHttpInterceptor extends OkHttpInterceptor {


    public SoapOkHttpInterceptor(int retryCount) {
        super(retryCount);
    }

    @Override
    protected Response buildSoapResponse(Request request, Response response) {
        SoapSerializationEnvelope envelope = request.tag(SoapSerializationEnvelope.class);
        ResponseBody body = response.body();
        if (body == null) {
            return response;
        }
        if (envelope != null) {
            // 对Xml进行处理
            try {
                Object result = envelope.parseResponse(body.byteStream());
                if (result != null) {
                    ResponseBody responseBody = ResponseBody.create(result.toString(), body.contentType());
                    return response.newBuilder().body(responseBody).build();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // soap 方法名
        HttpTag.Soap methodName = request.tag(HttpTag.Soap.class);
        if (methodName != null && methodName.name != null && methodName.name.length() != 0) {
            // 对Xml进行处理
            String parseXml = HttpSoapUtils.parseSoapXml(body.byteStream(), methodName.name);
            if (parseXml != null) {
                ResponseBody responseBody = ResponseBody.create(parseXml, body.contentType());
                return response.newBuilder().body(responseBody).build();
            }
        }
        return response;
    }
}
